package com.nineclock.message.service.impl;

import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.message.config.JPushManager;
import com.nineclock.message.dto.NcMessageDTO;
import com.nineclock.message.pojo.NcMessage;
import com.nineclock.message.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Service
@Slf4j
public class MessageServiceImpl implements MessageService {

    @Autowired
    JPushManager jPushManager;


    @Autowired
    MongoTemplate mongoTemplate;
    /**
     * 1. 推送消息给主管理员
     * 2. 消息存储到mongodb
     * @param message
     * @return
     * @throws Exception
     */
    @Override
    public Boolean pushSingleMessage(NcMessage message) throws Exception {
        //推送消息给主管理员
        jPushManager.sendNotificationByAlias(message.getTitle(), message.getContent(), message.getTargets(), null);
        //消息存储到mongodb
        mongoTemplate.save(message);

        return true;
    }

    @Override
    public List<NcMessage> findMessageRecord(NcMessageDTO ncMessageDTO) {
        if(ncMessageDTO == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        Query query = new Query();

        if(ncMessageDTO.getId() != null){
            query.addCriteria(Criteria.where("_id").is(ncMessageDTO.getId()));
        }
        if(ncMessageDTO.getType() != null){
            query.addCriteria(Criteria.where("messageType").is(ncMessageDTO.getType()));
        }
        if(ncMessageDTO.getUserId() != null){
            query.addCriteria(Criteria.where("applyUserId").is(ncMessageDTO.getUserId()));
        }
        if(ncMessageDTO.getTargetId() != null){
            query.addCriteria(Criteria.where("approveUserId").is(ncMessageDTO.getTargetId()));
        }
        query.with(Sort.by(Sort.Direction.ASC, "approveStatue"));

        List<NcMessage> messageList = mongoTemplate.find(query, NcMessage.class);
        return messageList;
    }

    @Override
    public void updateMessageWithApproved(String messageId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(messageId));

        Update update = new Update();
        update.set( "useStatus", 1);
        update.set( "approveStatue", 1);

        mongoTemplate.updateFirst(query ,update , NcMessage.class);
    }
}
